import React, { useState, useEffect } from "react";
import PubSub from "pubsub-js";
import {
  Card,
  Avatar,
  Switch,
  Row,
  Col,
  Popconfirm,
  Form,
  message,
} from "antd";
import { CloseOutlined, EditOutlined } from "@ant-design/icons";
import UpdateNetworkComponent from "../drawer/UpdateComponent.js";
import {
  editComponent,
  deleteComponent,
  getComponentList,
} from "../../../api/component/index";

function Cardtemplet() {

  //改动-------
  const componentList = getComponentList();
  console.log("componentList", componentList);
  //改动--------
  const { Meta } = Card;
  //isChange设置卡片状态
  const [isChange, setIsChange] = useState(componentList.concat());
  //通过isType的类型来显示卡片
  const [isType, setIsType] = useState("");
  const [forceupdate, setUpdate] = useState({});
  useEffect(() => {
    PubSub.unsubscribe("filterType");
    PubSub.unsubscribe("filterName");
    PubSub.subscribe("filterType", (msg, data) => {
      let a = data["key"];
      if (a === "全部") {
        setIsChange(componentList.concat());
        setIsType(data["key"]);
      } else {
        setIsType(data["key"]);
        let oldData = componentList.concat();
        let newData = oldData.filter((item) => {
          return item["type"].indexOf(a) !== -1;
        });
        setIsChange(newData.concat());
      }
    });
    PubSub.subscribe("filterName", (msg, data) => {
      let a = data["key"];
      setIsType(data["key"]);
      let oldData = componentList.concat();
      let newData = oldData.filter((item) => {
        return item["name"].indexOf(a) !== -1;
      });
      //改动-----------
      setIsChange(newData.concat());
    });
    PubSub.unsubscribe("reset2");
    //订阅----------------------------------------------------------------reset2
    PubSub.subscribe("reset2", (msg, data) => {
      if (isType !== "全部" && isType !== "") {
        let newData = componentList.filter((item) => {
          return item["type"].indexOf(isType) !== -1;
        });

        //改动---------
        setIsChange([...newData]);
      } else {
        ///改动---------
        console.log("setIsChange", componentList);
        setIsChange([...componentList]);
      }
    });
  }, [forceupdate]);

  const [updateForm] = Form.useForm();
  const cardsList = () => {
    let newList = [];

    for (let i = 0; i < isChange.length; i++) {
      newList.push(
        <Col span={6}>
          <Card
            style={{ width: "100%", marginTop: 15 }}
            actions={[
              <EditOutlined
                type="primary"
                onClick={() => {
                  //发送消息------------------------------------------------------------isUpdateCard，isUpdateCardId
                  PubSub.publish("isUpdateCard", { state: true });
                  PubSub.publish("isUpdateCardId", { id: isChange[i]["id"] });
                }}
              />,
              <Popconfirm
                title="确认删除此组件吗?"
                placement="topRight"
                onConfirm={() => {
                  let deleteResult = deleteComponent(isChange[i]["id"]);
                  //异步处理，等删除后在发送消息
                  deleteResult.then((item) => {
                    message.success(item["msg"]);
                    //发送消息----------------------------------------------------reset2，resetBar
                    PubSub.publish("reset2", true);
                    PubSub.publish("resetBar", isType);
                    //更新componentList
                    setUpdate({});
                  });
                }}
                okText="确定"
                cancelText="取消"
              >
                <CloseOutlined />
              </Popconfirm>,
            ]}
          >
            <Meta
              avatar={<Avatar size="small" />}
              title={isChange[i]["name"]}
              description={
                <div style={{ marginTop: 10 }}>
                  <Form form={updateForm} colon={false}>
                    <Row justify="space-between" align="middle">
                      <Col span={12}>
                        <span>组件类型</span>
                      </Col>
                      <Col span={12}>
                        <span>启动状态</span>
                      </Col>
                      <Form.Item
                        hidden={true}
                        name="id"
                        initialValue={isChange[i]["id"]}
                      ></Form.Item>
                      <Col span={4}>
                        <Form.Item
                          name="type"
                          initialValue={isChange[i]["type"]}
                        >
                          <span style={{ fontSize: "10px" }}>
                            {isChange[i]["type"]}
                          </span>
                        </Form.Item>
                      </Col>
                      <Col span={10}>
                        <Form.Item
                          name="state"
                          initialValue={
                            isChange[i]["state"]["value"] === "enabled"
                          }
                        >
                          <Popconfirm
                            title={`确认${
                              isChange[i]["state"]["value"] === "enabled"
                                ? "停止"
                                : "启动"
                            }吗?`}
                            onConfirm={() => {
                              let closeCardData = {};
                              closeCardData["state"] = {
                                text:
                                  isChange[i]["state"]["value"] === "enabled"
                                    ? "已停止"
                                    : "已启动",
                                value:
                                  isChange[i]["state"]["value"] === "enabled"
                                    ? "disabled"
                                    : "enabled",
                              };
                              closeCardData["name"] = isChange[i]["name"];
                              closeCardData["shareCluster"] =
                                isChange[i]["shareCluster"];
                              let updateResult = editComponent(
                                isChange[i]["id"],
                                closeCardData
                              );
                              updateResult.then((item) => {
                                message.success(item["msg"]);
                                PubSub.publish("reset2", true);
                              });
                            }}
                            okText="确定"
                            cancelText="取消"
                          >
                            <Switch
                              size="small"
                              checked={
                                isChange[i]["state"]["value"] === "enabled"
                              }
                            />
                          </Popconfirm>
                        </Form.Item>
                      </Col>
                    </Row>
                  </Form>
                </div>
              }
            />
          </Card>
        </Col>
      );
    }
    return newList;
  };

  return (
    <>
      {cardsList()}
      <UpdateNetworkComponent />
    </>
  );
}

export { Cardtemplet };
